#include "TGAImageDecoder.h"

void TGAImageDecoder::Decode(FILE *fp, Texture2D &image)
{
    TGA_HEADER   Header;
    fread ( &Header, sizeof(TGA_HEADER), 1, fp );


    image.width = Header.Width;
    image.height = Header.Height;
    image.channels = 3;

    if ( Header.ColorDepth == 24 ) 
    {
        ColorRGB *buffer24 = new ColorRGB[ image.width * image.height];
       
        if (buffer24)
        {
            unsigned int i=0;
            unsigned int x, y;

            fread(buffer24, sizeof(ColorRGB), image.width * image.height, fp);

            image.data = new unsigned char[image.width * image.height * image.channels];

            for ( y = 0; y < image.height; y++ )
            {
                for( x = 0; x < image.width; x++ )
                {
                    int index = y * (image.width) + x;

                    if(!(Header.Descriptor & INVERTED_BIT))
                        index = ((image.height) - 1 - y) * (image.width) + x;

                    image.data[(i * 3)] =  buffer24[index].r;
                    image.data[(i * 3) + 1] =  buffer24[index].g;
                    image.data[(i * 3) + 2] =  buffer24[index].b;

                    i++;
                }
            }
            delete buffer24;
        }		
    }

};
